package gmwxapplet

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"log"
	"path"
	"strings"
	"time"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/fddextsignuser"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/onlinesig"
)

//注册账号
func HandleAccountRegister(c *gin.Context) {
	accountRegisterModel := &request.AccountRegisterReq{}

	postData := map[string]string{}

	accountType := "2"
	openId := onlinesig.RandomStr(32)
	timeStr := time.Now().Format("20060102030405")

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + accountType + openId))
	//md5Str := strings.ToTitle(MD5(time.Now().Format("20060102030405")))
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	fmt.Println("shaStr1", shaStr1, "Md5", md5Str)

	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))

	accountRegisterModel.AppId = global.Cfg.Fdd.FddAppId
	accountRegisterModel.Timestamp = timeStr
	accountRegisterModel.OpenId = openId
	accountRegisterModel.AccountType = accountType
	accountRegisterModel.V = "2.0"
	accountRegisterModel.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&accountRegisterModel)
	json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/account_register.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//实名信息哈希存证
func HandleHashDeposit(c *gin.Context) {
	hashDepositModel := &request.HashDepositParam{}
	dingo.ErrorIf(c.Bind(hashDepositModel)).Unwrap()
	postData := map[string]string{}

	//签名
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + hashDepositModel.CertFlag + hashDepositModel.CustomerId + hashDepositModel.FileName +
		hashDepositModel.FileSize + hashDepositModel.NoperTime + hashDepositModel.OriginalSha256 + hashDepositModel.PreservationDesc +
		hashDepositModel.PreservationName + hashDepositModel.TransactionId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))

	hashDepositModel.AppId = global.Cfg.Fdd.FddAppId
	hashDepositModel.Timestamp = timeStr
	hashDepositModel.V = "2.0"
	hashDepositModel.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&hashDepositModel)
	json.Unmarshal(dataByte, &postData)
	//封装请求头
	headersMap := map[string]string{
		"Content-Type": " application/x-www-form-urlencoded;charset=utf8",
	}
	//测试环境
	urlStr := "https://textapi.fadada.com/api2/hash_deposit.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, headersMap)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//个人实名信息存证
func HandlePersonDeposit(c *gin.Context) {
	//接收字段参数
	personDepositModel := &request.PersonDepositReqParam{}
	dingo.ErrorIf(c.ShouldBindBodyWith(personDepositModel, binding.JSON)).Unwrap()

	//接收上传文件的路径
	personDepositFileModel := &request.PersonDepositFileParam{}
	dingo.ErrorIf(c.ShouldBindBodyWith(personDepositFileModel, binding.JSON)).Unwrap()

	postData := map[string]string{}

	//签名
	liveDetectionByte, err := json.Marshal(personDepositModel.LiveDetection)
	liveDetectionStr := string(liveDetectionByte)
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + personDepositModel.BankEssentialFactor + personDepositModel.CertFlag + personDepositModel.CustomerId +
		personDepositModel.DocumentType + personDepositModel.Idcard +
		liveDetectionStr +
		personDepositModel.Mobile + personDepositModel.MobileAndBankEssentialFactor +
		personDepositModel.MobileEssentialFactor + personDepositModel.Name + personDepositModel.PreservationDataProvider + personDepositModel.PreservationDesc + personDepositModel.PreservationName +
		personDepositModel.PublicSecurityEssentialFactor + personDepositModel.VerifiedTime + personDepositModel.VerifiedType))

	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	personDepositModel.AppId = global.Cfg.Fdd.FddAppId
	personDepositModel.Timestamp = timeStr
	personDepositModel.V = "2.0"
	personDepositModel.MsgDigest = msgDigest
	//转为Map
	dataByte, _ := json.Marshal(&personDepositModel)
	json.Unmarshal(dataByte, &postData)
	//封装请求头
	headersMap := map[string]string{
		"Content-Type": " application/x-www-form-urlencoded;charset=utf8",
	}

	//封装请求文件
	fileMap := map[string]string{}
	if personDepositFileModel.LiveDetectionFile != "" {
		ext := path.Ext(personDepositFileModel.LiveDetectionFile)
		fileMap[ext] = personDepositFileModel.LiveDetectionFile
	}
	if personDepositFileModel.IdcardNegativeFile != "" {
		ext := path.Ext(personDepositFileModel.IdcardNegativeFile)
		fileMap[ext] = personDepositFileModel.IdcardNegativeFile
	}

	if personDepositFileModel.IdcardPositiveFile != "" {
		ext := path.Ext(personDepositFileModel.IdcardPositiveFile)
		fileMap[ext] = personDepositFileModel.IdcardPositiveFile
	}

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/person_deposit.api"
	data, err := onlinesig.NewOnlineSig().PostWithFileFormData(urlStr, &postData, headersMap, fileMap)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
	}
	Response(c)("", CodeSuccess, data)(OK)

}

//企业实名信息存证
func HandleCompanyDeposit(c *gin.Context) {
	//接收字段参数
	companyDepositModel := &request.CompanyDepositParam{}
	dingo.ErrorIf(c.ShouldBindBodyWith(companyDepositModel, binding.JSON)).Unwrap()

	//接收上传文件的路径
	companyDepositFileModel := &request.CompanyDepositFileParam{}
	dingo.ErrorIf(c.ShouldBindBodyWith(companyDepositFileModel, binding.JSON)).Unwrap()

	//字段请求参数
	postData := map[string]string{}

	verifiedMsgByte, _ := json.Marshal(companyDepositModel.CompanyPrincipalVerifiedMsg)
	verifiedMsgByteStr := string(verifiedMsgByte)

	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + companyDepositModel.AmountOrRandomCode + companyDepositModel.CertFlag + companyDepositModel.CompanyName + companyDepositModel.CompanyPrincipalType +
		verifiedMsgByteStr + companyDepositModel.CreditCode + companyDepositModel.CustomerBank + companyDepositModel.CustomerBankAccount + companyDepositModel.CustomerBranchBank +
		companyDepositModel.CustomerId + companyDepositModel.LegalName + companyDepositModel.Licence + companyDepositModel.Organization + companyDepositModel.PayType + companyDepositModel.PreservationDataProvider +
		companyDepositModel.PreservationDesc + companyDepositModel.PreservationName + companyDepositModel.PublicBankAccount + companyDepositModel.PublicBranchBank + companyDepositModel.TransactionId +
		companyDepositModel.UserBackFillAmountOrRandomCode + companyDepositModel.VerifiedMode + companyDepositModel.VerifiedTime))

	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	companyDepositModel.AppId = global.Cfg.Fdd.FddAppId
	companyDepositModel.Timestamp = timeStr
	companyDepositModel.V = "2.0"
	companyDepositModel.MsgDigest = msgDigest
	//转为Map
	dataByte, _ := json.Marshal(&companyDepositModel)
	json.Unmarshal(dataByte, &postData)
	//封装请求头
	headersMap := map[string]string{
		"Content-Type": " application/x-www-form-urlencoded;charset=utf8",
	}

	//封装请求文件
	fileMap := map[string]string{}
	if companyDepositFileModel.LiveDetectionFile != "" {
		ext := path.Ext(companyDepositFileModel.LiveDetectionFile)
		fileMap[ext] = companyDepositFileModel.LiveDetectionFile
	}
	if companyDepositFileModel.IdcardNegativeFile != "" {
		ext := path.Ext(companyDepositFileModel.IdcardNegativeFile)
		fileMap[ext] = companyDepositFileModel.IdcardNegativeFile
	}

	if companyDepositFileModel.IdcardPositiveFile != "" {
		ext := path.Ext(companyDepositFileModel.IdcardPositiveFile)
		fileMap[ext] = companyDepositFileModel.IdcardPositiveFile
	}
	if companyDepositFileModel.CreditCodeFile != "" {
		ext := path.Ext(companyDepositFileModel.CreditCodeFile)
		fileMap[ext] = companyDepositFileModel.CreditCodeFile
	}

	if companyDepositFileModel.LicenceFile != "" {
		ext := path.Ext(companyDepositFileModel.LicenceFile)
		fileMap[ext] = companyDepositFileModel.LicenceFile
	}

	if companyDepositFileModel.OrganizationFile != "" {
		ext := path.Ext(companyDepositFileModel.OrganizationFile)
		fileMap[ext] = companyDepositFileModel.OrganizationFile
	}

	if companyDepositFileModel.PowerAttorneyFile != "" {
		ext := path.Ext(companyDepositFileModel.PowerAttorneyFile)
		fileMap[ext] = companyDepositFileModel.PowerAttorneyFile
	}

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/company_deposit.api"
	data, err := onlinesig.NewOnlineSig().PostWithFileFormData(urlStr, &postData, headersMap, fileMap)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
	}
	Response(c)("", CodeSuccess, data)(OK)

}

//编号证书申请
func HandleApplyClientNumCert(c *gin.Context) {
	param := &request.ApplyClientNumCert{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.CustomerId + param.EvidenceNo))
	//md5Str := strings.ToTitle(MD5(time.Now().Format("20060102030405")))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/apply_client_numcert.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//印章上传
func HandleAddSignature(c *gin.Context) {
	param := &request.AddSignature{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.CustomerId + param.SignatureImgBase64))
	//md5Str := strings.ToTitle(MD5(time.Now().Format("20060102030405")))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/add_signature.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//自定义印章

func HandleCustomSignature(c *gin.Context) {
	param := &request.CustomSignature{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.CustomerId + param.Content))
	//md5Str := strings.ToTitle(MD5(time.Now().Format("20060102030405")))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/custom_signature.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//合同上传
func UploadDocs(c *gin.Context) {
	param := &request.UploadDocs{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.ContractId))
	//md5Str := strings.ToTitle(MD5(time.Now().Format("20060102030405")))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/uploaddocs.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//模板上传
func UploadTemplate(c *gin.Context) {

	param := &request.UploadTemplate{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.TemplateId))
	//md5Str := strings.ToTitle(MD5(time.Now().Format("20060102030405")))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/uploadtemplate.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)

}

//模板填充
func GenerateContract(c *gin.Context) {
	param := &request.GenerateContract{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	parameterMapByte, err := json.Marshal(param.ParameterMap)
	parameterMapStr := string(parameterMapByte)

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.TemplateId + param.ContractId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1 + parameterMapStr)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	param.ParameterMap = parameterMapStr
	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/generate_contract.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)

}

//自动签署 ExtSignAuto
func ExtSignAuto(c *gin.Context) {
	param := &request.ExtSignAuto{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//userId, err := helper.GetUserIdFromCtx(c)
	//if err != nil {
	//	//dingo.ErrorIf(err).Unwrap()
	//	Response(c)("请重新登录", CodeError, nil)(Unauthorized)
	//	return
	//}
	//userId := 2
	////查询客户编号
	//fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(userId).Unwrap().(fddextsignuser.FddExtSignUser)
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeSuccess, nil)(Unauthorized)
		return
	}
	fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(userId).Unwrap().(fddextsignuser.FddExtSignUser)

	param.TransactionId = onlinesig.RandomStr(32)
	param.CustomerId = fddExtSignUserInfo.CustomerId
	param.ContractId = fddExtSignUserInfo.ContractId
	param.DocTitle = fddExtSignUserInfo.DocTitle
	param.NotifyUrl = global.Cfg.Fdd.FddNotifyUrl + "getVerifyNotify"
	param.SignKeyword = "乙方签署坐标"
	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.CustomerId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(param.TransactionId + timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))

	//Base64(FddEncryptTool.sha1(super.getAppId() + FddEncryptTool.md5Digest(transaction_id + timeStamp) + FddEncryptTool.sha1(super.getSecret() + customer_id)))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/extsign_auto.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//手动签署
func ExtSign(c *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeSuccess, nil)(Unauthorized)
		return
	}
	fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(userId).Unwrap().(fddextsignuser.FddExtSignUser)
	param := &request.ExtSign{}
	//dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	param.TransactionId = onlinesig.RandomStr(32)
	param.CustomerId = fddExtSignUserInfo.CustomerId
	param.ContractId = fddExtSignUserInfo.ContractId
	param.DocTitle = fddExtSignUserInfo.DocTitle
	//param.NotifyUrl = global.Cfg.Fdd.FddNotifyUrl + "getVerifyNotify"
	param.NotifyUrl = global.Cfg.Fdd.FddNotifyUrl + "getExtSignNotify"
	param.ReturnUrl = ""
	param.SignKeyword = "乙方签署坐标"
	param.OpenEnvironment = "1"

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.CustomerId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(param.TransactionId + timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	postData["urlStr"] = "https://textapi.fadada.com/api2/extsign.api"
	//headers := map[string]string{
	//	"User-Agent": c.Request.Header.Get("User-Agent"),
	//}

	//添加签署时间
	fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
	fddExtSignUserModel.SignedAt = dingo.Time(time.Now().Unix())
	fddExtSignUserModel.Id = fddExtSignUserInfo.Id
	memberdao.NewMemberDao().UpdateIsSignedAt(&fddExtSignUserModel).Unwrap()

	//测试环境
	//urlStr := "https://textapi.fadada.com/api2/extsign.api"
	//data, err := onlinesig.NewOnlineSig().PostWithFormDataReturnByte(urlStr, &postData, headers)
	//if err != nil {
	//	Response(c)("", CodeError, false)(OK)
	//}
	//c.HTML(200, "", string(data))
	c.JSON(200, postData)
	//Response(c)("", CodeSuccess, string(data))(OK)

}

//合同查看
func ViewContract(c *gin.Context) {
	reqParam := &struct {
		UserId int `json:"userId"`
	}{}
	dingo.ErrorIf(c.Bind(reqParam)).Unwrap()

	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeSuccess, nil)(Unauthorized)
		return
	}
	openId, _ := helper.GetUserNameFromCtx(c)

	if userId == 0 {
		userId = reqParam.UserId
	}
	log.Println("合同查看UserId", userId, openId)

	fddExtSignUserInfo := memberdao.NewMemberDao().GetExtSignInfo(userId).Unwrap().(fddextsignuser.FddExtSignUser)

	param := &request.ViewContract{}
	//dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}
	param.ContractId = fddExtSignUserInfo.ContractId

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.ContractId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)
	postData["urlStr"] = "https://textapi.fadada.com/api2/viewContract.api"

	log.Println("合同查看", postData, userId)
	//headers := map[string]string{
	//	"User-Agent": c.Request.Header.Get("User-Agent"),
	//}
	//
	////测试环境
	//urlStr := "https://textapi.fadada.com/api2/viewContract.api"
	//data, err := onlinesig.NewOnlineSig().PostWithFormDataReturnByte(urlStr, &postData, headers)
	//if err != nil {
	//	Response(c)("", CodeError, false)(OK)
	//	return
	//}
	//Response(c)("", CodeSuccess, string(data))(OK)

	c.JSON(200, postData)
}

//合同下载
func DownLoadContract(c *gin.Context) {
	param := &request.DownLoadContract{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.ContractId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/downLoadContract.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormDataReturnByte(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//合同归档
func ContractFiling(c *gin.Context) {
	param := &request.ContractFiling{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.ContractId))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest

	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/contractFiling.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//实名证书申请
func ApplyCert(c *gin.Context) {
	param := &request.ApplyCert{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}

	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.CustomerId + param.VerifiedSerialNo))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest
	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)

	//测试环境
	urlStr := "https://textapi.fadada.com/api2/apply_cert.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}
	Response(c)("", CodeSuccess, data)(OK)
}

//获取个人实名认证地址
func GetPersonVerifyUrl(c *gin.Context) {
	param := &request.GetPersonVerifyUrl{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}
	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.BankCardNo + param.CertFlag + param.CertType + param.CustomerId + param.CustomerIdentNo +
		param.CustomerIdentType + param.CustomerName + param.IdentBackPath + param.IdentFrontPath + param.Mobile + param.NotifyUrl + param.PageModify +
		param.ResultType + param.ReturnUrl + param.VerifiedWay))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest
	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)
	//测试环境
	urlStr := "https://textapi.fadada.com/api2/get_person_verify_url.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
	}
	resData := data["data"].(map[string]interface{})
	//解码
	decodeBytes, err := base64.StdEncoding.DecodeString(resData["url"].(string))
	if err != nil {
		log.Fatalln(err)
		return
	}
	fmt.Println(string(decodeBytes))

	Response(c)("", CodeSuccess, data)(OK)

}

//获取企业实名认证地址
func GetCompanyVerifyUrl(c *gin.Context) {

}

//查询个人实名认证信息
func FindPersonCertInfo(c *gin.Context) {
	param := &request.FindPersonCertInfo{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	postData := map[string]string{}
	//获取MsgDigest
	//获取MsgDigest
	shaStr1 := strings.ToTitle(onlinesig.SHA1(global.Cfg.Fdd.FddAppSecret + param.VerifiedSerialno))
	timeStr := time.Now().Format("20060102030405")
	md5Str := strings.ToTitle(onlinesig.MD5(timeStr))
	shaStr2 := onlinesig.SHA1(strings.ToTitle(global.Cfg.Fdd.FddAppId) + md5Str + shaStr1)
	msgDigest := onlinesig.Base64(strings.ToTitle(shaStr2))
	param.AppId = global.Cfg.Fdd.FddAppId
	param.Timestamp = timeStr
	param.V = "2.0"
	param.MsgDigest = msgDigest
	//转为Map
	dataByte, _ := json.Marshal(&param)
	_ = json.Unmarshal(dataByte, &postData)
	//测试环境
	urlStr := "https://textapi.fadada.com/api2/find_personCertInfo.api"
	data, err := onlinesig.NewOnlineSig().PostWithFormData(urlStr, &postData, nil)
	if err != nil {
		Response(c)("", CodeError, false)(OK)
		return
	}

	Response(c)("", CodeSuccess, data)(OK)
}

//获取实名认证异步回调
func GetVerifyNotify(c *gin.Context) {
	log.Println("实名异步回调过来了")
	reqData := &request.GetVerifyNotify{}
	dingo.ErrorIf(c.Bind(reqData)).Unwrap()
	log.Println("实名异步回调信息：", reqData)
	//实名认证成功
	if reqData.Status == "2" {
		//请求法大大实名证书申请
		data, err := onlinesig.GetVerifyApplyCert(reqData.CustomerId, reqData.SerialNo)
		if err != nil {
			Response(c)("实名认证失败", CodeSuccess, err)(OK)
			return
		}
		if data["msg"] != "success" {
			Response(c)("实名认证失败", CodeSuccess, err)(OK)
			return
		}
		//fddExtSignUserInfo := memberdao.NewMemberDao().GetUserInfoByCustomerId(reqData.CustomerId).Unwrap().(fddextsignuser.FddExtSignUser)
		//userInfo := dao.NewUserDao().GetUserInfoById(fddExtSignUserInfo.UserId).Unwrap().(*users.UserModel)
		certInfo, err := onlinesig.GetFindPersonCertInfo(reqData.SerialNo)
		if certInfo["status"].(string) != "2" || err != nil {
			Response(c)("实名认证失败", CodeSuccess, nil)(OK)
			return
		}

		//请求法大大实名证书申请
		applyCertData, err := onlinesig.GetVerifyApplyCert(reqData.CustomerId, reqData.SerialNo)
		if err != nil {
			Response(c)("实名认证失败", CodeSuccess, err)(OK)
			return
		}
		if applyCertData["msg"] != "success" {
			Response(c)("实名认证失败", CodeSuccess, err)(OK)
			return
		}
		contractId := onlinesig.RandomStr(32)
		docTitle := global.Cfg.Fdd.FddDocTitle
		templateId := global.Cfg.Fdd.FddTemplateId
		//请求法大大合同上传
		generateContractModel := request.GenerateContractParam{}

		//乙方填充内容
		generateContractModel.UserName = certInfo["personName"].(string)
		//generateContractModel.UserPhone = userInfo.Phone
		generateContractModel.UserPhone = certInfo["mobile"].(string)
		generateContractModel.UsersInfo = certInfo["personName"].(string) + "/" + certInfo["mobile"].(string)
		//generateContractModel.UsersInfo = userInfo.UserName + "-" + userInfo.Phone
		generateContractModel.UserYear = time.Now().Format("2006")
		generateContractModel.UserMonth = time.Now().Format("01")
		generateContractModel.UserDay = time.Now().Format("02")
		generateContractModel.ContractId = contractId
		//generateContractModel.ProPortion = strconv.Itoa(userInfo.ProfitProportion)
		//甲方填充内容
		generateContractModel.Year = time.Now().Format("2006")
		generateContractModel.Month = time.Now().Format("01")
		generateContractModel.Day = time.Now().Format("02")
		err = onlinesig.GenerateContract(generateContractModel, contractId, docTitle, templateId)
		if err != nil {
			Response(c)("实名认证失败", CodeSuccess, err)(OK)
			return
		}

		//修改数据库中is_ext=2已实名
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		fddExtSignUserModel.CustomerId = reqData.CustomerId
		fddExtSignUserModel.IsExt = 2
		memberdao.NewMemberDao().UpdateIdIsExtByCustomer(&fddExtSignUserModel).Unwrap()

		Response(c)("实名认证成功", CodeSuccess, true)(OK)

	}

	Response(c)("", CodeSuccess, false)(OK)

}

//{
//i8aVDN9q8K80HyVbvnKHka6gMB7cfWyp
//VQrHQmgZm4efuQ57Dljg3KzpcSi15oVM
//3000
//签章成功
//https://testapi.fadada.com:8443/api//getdocs.action?app_id=404577&timestamp=20210621170405&v=2.0&msg_digest=REUxQkI2MTkwODM1RTNDRkJGMDlENUM1MThBOUFBNDg3ODg3NDZFNQ==&transaction_id=i8aVDN9q8K80HyVbvnKHka6gMB7cfWyp&send_app_id=null
//https://testapi.fadada.com:8443/api//viewdocs.action?app_id=404577&timestamp=20210621170405&v=2.0&msg_digest=REUxQkI2MTkwODM1RTNDRkJGMDlENUM1MThBOUFBNDg3ODg3NDZFNQ==&transaction_id=i8aVDN9q8K80HyVbvnKHka6gMB7cfWyp&send_app_id=null
//20210621170448
//OEI5RDc5QkIyRjdBOEVFNkYwQjdDOUE1RTczOUYyNDRDMTQwNUU5RA==}

func GetExtSignNotify(c *gin.Context) {
	log.Println("签署异步回调过来了")
	reqData := &request.GetExtSignNotify{}
	dingo.ErrorIf(c.Bind(reqData)).Unwrap()
	log.Println("签署异步回调信息：", reqData)

	//签署成功修改状态
	if reqData.ResultCode == "3000" && reqData.ContractId != "" {
		fddExtSignUserModel := fddextsignuser.FddExtSignUser{}
		fddExtSignUserModel.ContractId = reqData.ContractId
		fddExtSignUserModel.IsSigned = 2
		fddExtSignUserModel.SignContractUrl = reqData.DownloadUrl
		memberdao.NewMemberDao().UpdateByContractId(&fddExtSignUserModel).Unwrap()

		//合同归档
		err := onlinesig.ContractIdFiling(reqData.ContractId)
		if err != nil {
			Response(c)("", CodeError, false)(OK)
			return
		}
		Response(c)("", CodeSuccess, true)(OK)
		return
	}
	Response(c)("", CodeError, false)(OK)
}
